//
//  DBBaseViewController.swift
//  DBCA
//
//  Created by mugua on 2024/6/30.
//

import UIKit

class DBBaseViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configIOS11()
        configIOS15()
        
        if self.navigationController != nil {
            if self.navigationController!.viewControllers.count != 1 {
                self.navigationItem.leftBarButtonItem = backBarButtonItem
            } else {
                self.navigationItem.hidesBackButton = true
            }
        }
    }
    
    private var backBarButtonItem: UIBarButtonItem? {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        button.setImage(UIImage(named: "nav_back"), for: .normal)
        button.setImage(UIImage(named: "nav_back"), for: .highlighted)
        button.addTarget(self, action: #selector(back), for: .touchUpInside)
        return UIBarButtonItem(customView: button)
    }
    
    @objc func back() {
        if (self.navigationController != nil) {
            if self.navigationController!.viewControllers.count > 1 {
                self.navigationController?.popViewController(animated: true)
            } else {
                self.navigationController?.dismiss(animated: true)
            }
        } else {
            self.dismiss(animated: true)
        }
    }
    
    func configIOS11() {
        if #available(iOS 11.0, *) {
            UITableView.appearance().estimatedRowHeight = 0
            UITableView.appearance().estimatedSectionHeaderHeight = 0
            UITableView.appearance().estimatedSectionFooterHeight = 0
            UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
            UITableView.appearance().contentInsetAdjustmentBehavior = .never
            UICollectionView.appearance().contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
    }
    
    func configIOS15() {
        if #available(iOS 15.0, *) {
            UITableView.appearance().sectionHeaderTopPadding = 0
        }
    }
}
